package com.example.pt.controller;


import com.example.pt.entity.User;
import com.example.pt.service.UserService;
import com.example.pt.task.UserAssessmentTask;
import com.example.pt.utils.DownloadUrlUtils;
import com.example.pt.utils.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.sql.Date;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/login")
@CrossOrigin(origins = "*")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(UserAssessmentTask.class);

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private DownloadUrlUtils downloadUrlUtils;

    //登录接口
    @PostMapping("")
    public ResponseEntity<Map<String, Object>> Login(@RequestBody Map<String, String> loginData) { // uid passwrod
        int uid = Integer.valueOf(loginData.get("uid"));
        String password = loginData.get("password");

        Map<String, Object> response = new HashMap<>();

        User user = userService.searchByUid(uid);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            if (user.getUsertype() == 1) {
                if(user.getStatus() == 1){ // 1被封禁
                    response.put("status","fail");
                    response.put("message","您违反社区规定已被封禁，详情请找管理员了解！");
                    return new ResponseEntity<>(response, HttpStatus.OK);
                }
                if(user.getStatus() == 2 || user.getStatus() == 0){// 0是正常，2是不符合规范但是在缓冲期

                    Date loginDate = Date.valueOf(LocalDate.now());
                    userService.setLastLoginTime(uid, loginDate);
                    response.put("userType", 1);
                    response.put("uid", uid);
                    response.put("message", "登录成功！");
                    response.put("status", "success");
                    //获取用户头像下载链接
                    String headshotUrl = downloadUrlUtils.generateDownloadLink(uid);

                    response.put("headshot", headshotUrl);
                    response.put("token", JWTUtil.generateToken(user.getUsertype(), user.getUid()));
                    return new ResponseEntity<>(response, HttpStatus.OK);
                }
            } else if (user.getUsertype() == 0) {
                logger.info("管理员{}" + user.getUid() + "登录");
                response.put("userType", 0);
                response.put("uid", uid);
                response.put("message", "登录成功！");
                response.put("status", "success");

                response.put("token", JWTUtil.generateToken(user.getUsertype(), user.getUid()));

                LocalDate localDate = LocalDate.now();

               if(userService.setLastLoginTime(uid,Date.valueOf(localDate))){

                System.out.println("*************************************************************" +
                        "************************************"+ userService.setLastLoginTime(uid,Date.valueOf(localDate)) +Date.valueOf(localDate));
               }

                return new ResponseEntity<>(response, HttpStatus.OK);
            }
        }
        response.put("message", "登录失败，用户名或密码错误！");
        response.put("status", "fail");
        return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
    }
}
